from khronos import Atomic

class Router(Atomic):
    def __init__(self, rules=(), name=None, parent=None, priority=None):
        Atomic.__init__(self, name, parent, priority)
        self.__routed = 0
        self.rules = list(rules)
        
    def initializer(self):
        self.__routed = 0
        
    def receive(self, obj, src):
        for rule in self.rules:
            dst = rule(obj, src)
            if dst is not None:
                self.__routed += 1
                src.send(obj, dst)
        raise ValueError("no routing rule for %s sent by %s" % (obj, src))
        
    def status(self):
        return "routed %d objects" % (self.__routed,)
        
